import random

from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection


from libs.captcha.captcha import captcha

from meiduo_mall.settings.dev import logger

from libs.yuntongxun.sms import CCP

class SMSCodeView(View):
    '''
    校验图片验证码以及发送短信验证码
    '''
    # http://www.meiduo.site:8000/sms_codes/18839139652/?image_code=1324&image_code_id=4c30ad74-a366-4b99-afd7-60a191a23580
    def get(self, request, mobile):
        # 1.J解析教研组参数
        uuid = request.GET.get('image_code_id')
        image_code = request.GET.get('image_code')

        try:
            # 2.校验图形验证码
            # 2.1根据uuid去reids数据哭查询验证码
            redis_cli = get_redis_connection('verify_image_code')
            redis_code = redis_cli.get('img_%s' % uuid)
            # 2.2判断并返回

            if redis_code is None:
                return JsonResponse({'code':'4001', 'errmsg':'图形验证码失效'})
            if redis_code.decode().lower() != image_code.lower():
                return JsonResponse({'code':'4001', 'msg':'图形验证码错误'})
            redis_cli.delete('img%s' % uuid)
        except Exception as e:
            logger.error(e)

        sms_code = '%06d' % random.randint(0, 999999)

        try:
            sms_redis_client = get_redis_connection('sms_code')   #链接数据库
            sms_redis_client.setex('sms_%s' % mobile, 300, sms_code)
        except Exception as e:
            logger.error(e)

        print(sms_code)

        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        # CCP().send_template_sms('18839139652', ['123456', 5], 1)
        from celery_tasks.sms.tasks import ccp_send_sms_code
        ccp_send_sms_code.delay(mobile, sms_code)
        return JsonResponse({'code':'0', 'errmsg':'发送短信成功'})









class ImageCodeView(View):
    def get(self, request, uuid):
        '''获取图片验证码'''
        # 生成图片验证码
        text, image = captcha.generate_captcha()
        # 保存图片验证码

        redis_client = get_redis_connection('verify_image_code')  # 链接redis数据库
        redis_client.setex('img_%s' % uuid, 300, text)
        return HttpResponse(image, content_type='image/jpg')

#
# class Index(View):
#
#
#     def get(self, request):
#
#         return 'hello world'